<template>
  <div>
    <div style="text-align: center">
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8081/user/uploadAvatar"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :headers="head"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <div style="text-align: center">
      <p>上传图片最好为：200 * 200</p>
      <p>只能上传小于2MB的图片</p>
      <p>图片格式只能为：jpeg, jpg, png, gif</p>
    </div>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<script>
export default {
  data() {
    return {
      file: "",
      imageUrl: "",
      head: {
        Authorization: localStorage.getItem("token"),
      },
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.avatar;
      this.$store.commit("SET_USERINFO", res.data);
      this.file = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG || !isPNG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
  },
  created() {
    this.imageUrl = this.$store.getters.getUser.avatar;
  },
};
</script>
